package main

import (
	"context"
	"fmt"
	"gitee.com/DonHz/electronic-business-systems/grpc_test/proto"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"google.golang.org/grpc/status"
	"time"
)

type CustomCredential struct {
}

func (c CustomCredential) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
	return map[string]string{
		"appid":  "i am appid",
		"appkey": "i am appkey",
	}, nil
}

func (c CustomCredential) RequireTransportSecurity() bool {
	return false
}

func main() {
	//interceptor := func(ctx context.Context, method string, req, reply any, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {
	//	start := time.Now()
	//	md := metadata.New(map[string]string{
	//		"appid":  "i am appid",
	//		"appkey": "i am appkey",
	//	})
	//	ctx = metadata.NewOutgoingContext(ctx, md)
	//	err := invoker(ctx, method, req, reply, cc, opts...)
	//	fmt.Println("耗时： ", time.Since(start))
	//	return err
	//}
	//grpc.WithPerRPCCredentials(CustomCredential{})
	var opts []grpc.DialOption
	opts = append(opts, grpc.WithTransportCredentials(insecure.NewCredentials()))
	opts = append(opts, grpc.WithPerRPCCredentials(CustomCredential{}))
	conn, err := grpc.NewClient("127.0.0.1:8080", opts...)
	if err != nil {
		panic(err)
	}
	defer conn.Close()
	c := proto.NewHelloClient(conn)
	ctx, _ := context.WithTimeout(context.Background(), time.Second*3)
	resp, err := c.Hello(ctx, &proto.HelloRequest{Name: "Tom", Age: 11})
	if err != nil {
		st, ok := status.FromError(err)
		if !ok {
			panic("解析error失败")
		}
		fmt.Println(st.Message())
		fmt.Println(st.Code())
		return
	}
	fmt.Println(resp.Reply)
}
